<script setup lang="ts">
import { ref, reactive, onMounted, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus, Edit, Delete, Search } from '@element-plus/icons-vue'
import request from '@/utils/request'

// 현재 활성 탭
const activeTab = ref<'notice' | 'faq'>('notice')

// 목록 데이터
const noticeList = ref<any[]>([])
const faqList = ref<any[]>([])

// 페이지네이션 정보
const noticePagination = reactive({
  page: 1,
  limit: 20,
  total: 0
})

const faqPagination = reactive({
  page: 1,
  limit: 20,
  total: 0
})

// 검색 키워드
const searchQuery = ref('')

// 로딩 상태
const loading = ref(false)

// 폼 관련
const dialogVisible = ref(false)
const dialogTitle = ref('')
const isEditing = ref(false)
const currentId = ref<string | null>(null)

const form = reactive({
  title: '',
  content: '',
  isPinned: false,
  isPublished: false
})

// 현재 목록 및 페이지네이션 계산
const currentList = computed(() => activeTab.value === 'notice' ? noticeList.value : faqList.value)
const currentPagination = computed(() => activeTab.value === 'notice' ? noticePagination : faqPagination)

// API 기본 경로
const getApiPath = (type: 'notice' | 'faq') => {
  return type === 'notice' ? '/api/admin/notices' : '/api/admin/faqs'
}

// 목록 데이터 가져오기
const fetchList = async () => {
  loading.value = true
  try {
    const apiPath = getApiPath(activeTab.value)
    const params = {
      page: currentPagination.value.page,
      limit: currentPagination.value.limit,
      ...(searchQuery.value && { q: searchQuery.value })
    }

    const response = await request.get(apiPath, { params })
    const { items, total } = response.data

    if (activeTab.value === 'notice') {
      noticeList.value = items
      noticePagination.total = total
    } else {
      faqList.value = items
      faqPagination.total = total
    }
  } catch (error) {
    console.error('목록 가져오기 실패:', error)
    ElMessage.error('목록 가져오기 실패')
  } finally {
    loading.value = false
  }
}

// 탭 전환
const handleTabChange = (tab: string) => {
  activeTab.value = tab as 'notice' | 'faq'
  searchQuery.value = ''
  fetchList()
}

// 검색
const handleSearch = () => {
  currentPagination.value.page = 1
  fetchList()
}

// 페이지 변경
const handlePageChange = (page: number) => {
  currentPagination.value.page = page
  fetchList()
}

const handleSizeChange = (size: number) => {
  currentPagination.value.limit = size
  currentPagination.value.page = 1
  fetchList()
}

// 폼 초기화
const resetForm = () => {
  form.title = ''
  form.content = ''
  form.isPinned = false
  form.isPublished = false
  currentId.value = null
  isEditing.value = false
}

// 추가
const handleAdd = () => {
  resetForm()
  dialogTitle.value = `${activeTab.value === 'notice' ? '공지사항' : 'FAQ'} 추가`
  dialogVisible.value = true
}

// 编辑
const handleEdit = (row: any) => {
  resetForm()
  isEditing.value = true
  currentId.value = row.id
  form.title = row.title
  form.content = row.content
  form.isPinned = row.isPinned
  form.isPublished = row.isPublished
  dialogTitle.value = `${activeTab.value === 'notice' ? '공지사항' : 'FAQ'} 편집`
  dialogVisible.value = true
}

// 删除
const handleDelete = async (row: any) => {
  try {
    await ElMessageBox.confirm(
      `이 ${activeTab.value === 'notice' ? '공지사항' : 'FAQ'}을 삭제하시겠습니까?`,
      '삭제 확인',
      {
        confirmButtonText: '확인',
        cancelButtonText: '취소',
        type: 'warning'
      }
    )

    const apiPath = getApiPath(activeTab.value)
    await request.delete(`${apiPath}/${row.id}`)
    ElMessage.success('삭제 성공')
    fetchList()
  } catch (error: any) {
    if (error !== 'cancel') {
      console.error('삭제 실패:', error)
      ElMessage.error('삭제 실패')
    }
  }
}

// 保存
const handleSave = async () => {
  if (!form.title.trim() || !form.content.trim()) {
    ElMessage.error('제목과 내용은 비워둘 수 없습니다')
    return
  }

  try {
    const apiPath = getApiPath(activeTab.value)
    const data = {
      title: form.title.trim(),
      content: form.content.trim(),
      isPinned: form.isPinned,
      isPublished: form.isPublished
    }

    if (isEditing.value && currentId.value) {
      await request.put(`${apiPath}/${currentId.value}`, data)
      ElMessage.success('업데이트 성공')
    } else {
      await request.post(apiPath, data)
      ElMessage.success('생성 성공')
    }

    dialogVisible.value = false
    fetchList()
  } catch (error) {
    console.error('저장 실패:', error)
    ElMessage.error('저장 실패')
  }
}

// 格式化日期
const formatDate = (dateStr: string) => {
  return new Date(dateStr).toLocaleString('zh-CN')
}

onMounted(() => {
  fetchList()
})
</script>

<template>
  <div class="notice-faq-management">
    <div class="header">
      <h2>공지사항 및 FAQ 관리</h2>
    </div>

    <!-- 탭 전환 -->
    <el-tabs v-model="activeTab" @tab-change="handleTabChange" class="tabs">
      <el-tab-pane label="공지사항 관리" name="notice" />
      <el-tab-pane label="FAQ 관리" name="faq" />
    </el-tabs>

    <!-- 작업 도구 모음 -->
    <div class="toolbar">
      <div class="toolbar-left">
        <el-button type="primary" :icon="Plus" @click="handleAdd">
          {{ activeTab === 'notice' ? '공지사항' : 'FAQ' }} 추가
        </el-button>
      </div>
      <div class="toolbar-right">
        <el-input
          v-model="searchQuery"
          placeholder="제목 검색..."
          style="width: 300px"
          clearable
          @keyup.enter="handleSearch"
        >
          <template #append>
            <el-button :icon="Search" @click="handleSearch" />
          </template>
        </el-input>
      </div>
    </div>

    <!-- 목록 -->
    <el-table :data="currentList" v-loading="loading" stripe>
      <el-table-column prop="title" label="제목" min-width="200" show-overflow-tooltip />
      <el-table-column prop="isPinned" label="고정" width="80" align="center">
        <template #default="{ row }">
          <el-tag v-if="row.isPinned" type="warning" size="small">고정</el-tag>
          <span v-else>-</span>
        </template>
      </el-table-column>
      <el-table-column prop="isPublished" label="발행 상태" width="100" align="center">
        <template #default="{ row }">
          <el-tag :type="row.isPublished ? 'success' : 'info'" size="small">
            {{ row.isPublished ? '발행됨' : '초안' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="createdAt" label="생성 시간" width="180">
        <template #default="{ row }">
          {{ formatDate(row.createdAt) }}
        </template>
      </el-table-column>
      <el-table-column label="작업" width="150" align="center">
        <template #default="{ row }">
          <el-button type="primary" :icon="Edit" size="small" @click="handleEdit(row)">
            편집
          </el-button>
          <el-button type="danger" :icon="Delete" size="small" @click="handleDelete(row)">
            삭제
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 페이지네이션 -->
    <div class="pagination">
      <el-pagination
        v-model:current-page="currentPagination.page"
        v-model:page-size="currentPagination.limit"
        :page-sizes="[10, 20, 50, 100]"
        :total="currentPagination.total"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handlePageChange"
      />
    </div>

    <!-- 편집 대화상자 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogTitle"
      width="600px"
      :close-on-click-modal="false"
    >
      <el-form :model="form" label-width="80px">
        <el-form-item label="제목" required>
          <el-input v-model="form.title" placeholder="제목을 입력하세요" />
        </el-form-item>
        <el-form-item label="내용" required>
          <el-input
            v-model="form.content"
            type="textarea"
            :rows="8"
            placeholder="내용을 입력하세요"
          />
        </el-form-item>
        <el-form-item label="옵션">
          <el-checkbox v-model="form.isPinned">고정</el-checkbox>
          <el-checkbox v-model="form.isPublished">발행</el-checkbox>
        </el-form-item>
      </el-form>

      <template #footer>
        <el-button @click="dialogVisible = false">취소</el-button>
        <el-button type="primary" @click="handleSave">저장</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<style scoped>
.notice-faq-management {
  padding: 20px;
}

.header {
  margin-bottom: 20px;
}

.header h2 {
  margin: 0;
  color: var(--el-text-color-primary);
}

.tabs {
  margin-bottom: 20px;
}

.toolbar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.toolbar-left {
  display: flex;
  gap: 12px;
}

.toolbar-right {
  display: flex;
  gap: 12px;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}

/* 반응형 디자인 */
@media (max-width: 768px) {
  .notice-faq-management {
    padding: 16px;
  }

  .toolbar {
    flex-direction: column;
    gap: 16px;
    align-items: stretch;
  }

  .toolbar-right {
    justify-content: center;
  }
}
</style>
